//
//  NSURL+Tools.m
//  Pods
//
//  Created by jiaxuzhou on 2017/7/13.
//
//

#import "NSURL+Tools.h"

@implementation NSURL (Tools)


- (NSURL *)mp_UrlByAppendingQueryString:(NSString *)queryString
{
    if (![queryString length])
    {
        return self;
    }
    
    if ([self fragment])
    {
        NSString *fragment = [self fragment];
        NSRange range = [self.absoluteString rangeOfString:[NSString stringWithFormat:@"%@",fragment]];
        if (range.location != NSNotFound)
        {
            NSString *locationURL = [self.absoluteString substringToIndex:range.location-1];
            NSString *urlStr = [[NSString alloc] initWithFormat:@"%@%@%@#%@", locationURL,
                                [[NSURL URLWithString:locationURL] query] ? @"&" : @"?", queryString,fragment];
            NSURL *url = [NSURL URLWithString:urlStr];
            return url;
        }
    }
    
    NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", [self absoluteString],
                           [self query] ? @"&" : @"?", queryString];
    NSURL *theURL = [NSURL URLWithString:URLString];
    
    return theURL;
}


@end
